package com.levi.interceptor;

import com.alibaba.fastjson.JSON;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author shentong
 * @since 2022/7/26 21:42
 */
@Component
@Slf4j
public class LogInterceptor implements AsyncHandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		String token = request.getHeader("token");
		log.info("{} - request:>>{}", token, request.toString());
		if (token != null) {
			MDC.put("token", token);
		}
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		String token = MDC.get("token");
		MDC.clear();
		log.info("{} - request:>>{}", token, response.toString());
	}

}
